package com.booksystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.booksystem.common.BusinessException;
import com.booksystem.common.ResultCodeConstant;
import com.booksystem.dto.UserInfoUpdateDTO;
import com.booksystem.dto.UserLoginDTO;
import com.booksystem.dto.UserPasswordUpdateDTO;
import com.booksystem.dto.UserRegisterDTO;
import com.booksystem.entity.UserDO;
import com.booksystem.mapper.UserMapper;
import com.booksystem.service.UserService;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *   用户服务实现类
 * </p>
 * @author 段伟豪
 */
@Slf4j
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Boolean register(UserRegisterDTO userRegisterDTO) {
        // 检查用户名是否已存在
        QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userRegisterDTO.getUsername());
        UserDO existingUserByUsername = userMapper.selectOne(wrapper);
        if (existingUserByUsername != null) {
            throw new BusinessException(ResultCodeConstant.CODE_USER_EXISTS, ResultCodeConstant.CODE_USER_EXISTS_MSG);
        }

        // 检查邮箱是否已被注册
        wrapper.clear();
        wrapper.eq("email", userRegisterDTO.getEmail());
        UserDO existingUserByEmail = userMapper.selectOne(wrapper);
        if (existingUserByEmail != null) {
            throw new BusinessException(ResultCodeConstant.CODE_EMAIL_EXISTS, ResultCodeConstant.CODE_EMAIL_EXISTS_MSG);
        }

        // 插入新用户
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userRegisterDTO, userDO);
        userDO.setCreateTime(new Date());
        userDO.setUpdateTime(new Date());
        userDO.setStatus(1); // 默认启用状态
        int insertCount = userMapper.insert(userDO);
        return insertCount > 0;
    }

    @Override
    public UserDO login(UserLoginDTO loginDTO) {
        // 根据用户名查找用户
        QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
        wrapper.eq("username", loginDTO.getUsername());
        UserDO userDO = userMapper.selectOne(wrapper);
        if (userDO == null) {
            throw new BusinessException(ResultCodeConstant.CODE_USER_NOT_FOUND, ResultCodeConstant.CODE_USER_NOT_FOUND_MSG);
        }

        // 验证密码
        if (!userDO.getPasswordHash().equals(loginDTO.getPasswordHash())) {
            throw new BusinessException(ResultCodeConstant.CODE_PASSWORD_ERROR, ResultCodeConstant.CODE_PASSWORD_ERROR_MSG);
        }

        return userDO;
    }

    @Override
    public Boolean updateUserInfo(UserInfoUpdateDTO userInfoUpdateDTO) {
        // 查询用户是否存在
        UserDO existingUser = userMapper.selectById(userInfoUpdateDTO.getUserId());
        if (existingUser == null) {
            throw new BusinessException(ResultCodeConstant.CODE_USER_INFO_NOT_FOUND, ResultCodeConstant.CODE_USER_INFO_NOT_FOUND_MSG);
        }

        // 更新用户信息
        UserDO updateUser = new UserDO();
        updateUser.setUserId(userInfoUpdateDTO.getUserId());
        updateUser.setPhone(userInfoUpdateDTO.getPhone());
        updateUser.setRealName(userInfoUpdateDTO.getRealName());
        updateUser.setAvatarUrl(userInfoUpdateDTO.getAvatarUrl());
        updateUser.setUpdateTime(new Date());

        int updateCount = userMapper.updateById(updateUser);
        return updateCount > 0;
    }

    @Override
    public Boolean updatePassword(UserPasswordUpdateDTO passwordUpdateDTO) {
        // 查找用户是否存在
        UserDO existingUser = userMapper.selectById(passwordUpdateDTO.getUserId());
        if (existingUser == null) {
            throw new BusinessException(ResultCodeConstant.CODE_USER_INFO_NOT_FOUND, ResultCodeConstant.CODE_USER_INFO_NOT_FOUND_MSG);
        }

        // 验证原始密码
        if (!existingUser.getPasswordHash().equals(passwordUpdateDTO.getOldPasswordHash())) {
            throw new BusinessException(ResultCodeConstant.CODE_OLD_PASSWORD_ERROR, ResultCodeConstant.CODE_OLD_PASSWORD_ERROR_MSG);
        }

        // 更新密码
        existingUser.setPasswordHash(passwordUpdateDTO.getNewPasswordHash());
        existingUser.setUpdateTime(new Date());

        int updateCount = userMapper.updateById(existingUser);
        return updateCount > 0;
    }
}